package cn.may.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author mayuanbao
 * @date 2019-06-09 17:27
 */
public class WordUtil {
    public static Boolean exportWord(Map<String,Object> dataMap, String templateName) {
        // 初始化配置文件
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
        // 设置编码
        configuration.setDefaultEncoding("UTF-8");
        try {
            // 模板路径
            String path = ResourceUtils.getURL("classpath:").getPath() + "static/moudle";
            //加载文件
            configuration.setDirectoryForTemplateLoading(new File(path));
            Template template = configuration.getTemplate(templateName);
            // 输出word文件路径
            String outPath = "F:/student" + UUID.randomUUID().toString().replace("-", "") + ".doc";
            File file = new File(outPath);
            FileOutputStream out = new FileOutputStream(file);
            // 输出
            Writer writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8), 10240);
            template.process(dataMap, writer);
            writer.close();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
        return true;
    }
}
